
/**************************** This code generates the main results in the paper (2 figures and 10 tables)  *************************/
* ``Commonality in Credit Spread Changes: Dealer Inventory and Intermediary Distress" (RFS forthcoming)
*                           by Zhiguo He, Paymon Khorrami, and Zhaogang Song,  
 
	

	
  /***  Table 1:  summary of the quarterly data sample  ***/
        *(issue_size in $million, IG bond has rating_scale<=10 or rating_moody as good as or better than Baa3)
clear
use Pseudo4RFS_corp_base_sample_4reg_quarterly_final      /* The first two rows in each panel of Table 1 can be read from "n_bonds_all" "n_firms_rating" "n_bonds_rating"  "n_firms_all"  */
  	*all sample
estpost tabstat ys, statistics(N mean sd p25 p50 p75) columns(statistics) listwise   
esttab using corp_sample_sumstat.tex, cells("count(fmt(0))  mean(fmt(2)) sd(fmt(2)) p25(fmt(2)) p50(fmt(2)) p75(fmt(2))") replace  
estpost tabstat coupon, statistics(N mean sd p25 p50 p75  ) columns(statistics) listwise   
esttab using corp_sample_sumstat.tex, cells("count(fmt(0))  mean(fmt(2)) sd(fmt(2)) p25(fmt(2)) p50(fmt(2)) p75(fmt(2))") append   
estpost tabstat time2mature, statistics(N mean sd p25 p50 p75  ) columns(statistics) listwise   
esttab using corp_sample_sumstat.tex, cells("count(fmt(0))  mean(fmt(2)) sd(fmt(2)) p25(fmt(2)) p50(fmt(2)) p75(fmt(2))") append   
estpost tabstat age, statistics(N mean sd p25 p50 p75  ) columns(statistics) listwise   
esttab using corp_sample_sumstat.tex, cells("count(fmt(0))  mean(fmt(2)) sd(fmt(2)) p25(fmt(2)) p50(fmt(2)) p75(fmt(2))") append   
estpost tabstat issue_size, statistics(N mean sd p25 p50 p75  ) columns(statistics) listwise   
esttab using corp_sample_sumstat.tex, cells("count(fmt(0))  mean(fmt(2)) sd(fmt(2)) p25(fmt(2)) p50(fmt(2)) p75(fmt(2))") append   
estpost tabstat rating_scale, statistics(N mean sd p25 p50 p75  ) columns(statistics) listwise   
esttab using corp_sample_sumstat.tex, cells("count(fmt(0))  mean(fmt(2)) sd(fmt(2)) p25(fmt(2)) p50(fmt(2)) p75(fmt(2))") append   

    *IG sample	
keep if rating_scale<=10
estpost tabstat ys, statistics(N mean sd p25 p50 p75 ) columns(statistics) listwise   
esttab using corp_sample_sumstat.tex, cells("count(fmt(0))  mean(fmt(2)) sd(fmt(2)) p25(fmt(2)) p50(fmt(2)) p75(fmt(2))") append    
estpost tabstat coupon, statistics(N mean sd p25 p50 p75  ) columns(statistics) listwise   
esttab using corp_sample_sumstat.tex, cells("count(fmt(0))  mean(fmt(2)) sd(fmt(2)) p25(fmt(2)) p50(fmt(2)) p75(fmt(2))") append   
estpost tabstat time2mature, statistics(N mean sd p25 p50 p75 ) columns(statistics) listwise   
esttab using corp_sample_sumstat.tex, cells("count(fmt(0))  mean(fmt(2)) sd(fmt(2)) p25(fmt(2)) p50(fmt(2)) p75(fmt(2))") append   
estpost tabstat age, statistics(N mean sd p25 p50 p75 ) columns(statistics) listwise   
esttab using corp_sample_sumstat.tex, cells("count(fmt(0))  mean(fmt(2)) sd(fmt(2)) p25(fmt(2)) p50(fmt(2)) p75(fmt(2))") append   
estpost tabstat issue_size, statistics(N mean sd p25 p50 p75 ) columns(statistics) listwise   
esttab using corp_sample_sumstat.tex, cells("count(fmt(0))  mean(fmt(2)) sd(fmt(2)) p25(fmt(2)) p50(fmt(2)) p75(fmt(2))") append   
estpost tabstat rating_scale, statistics(N mean sd p25 p50 p75 ) columns(statistics) listwise   
esttab using corp_sample_sumstat.tex, cells("count(fmt(0))  mean(fmt(2)) sd(fmt(2)) p25(fmt(2)) p50(fmt(2)) p75(fmt(2))") append   
   
	*HY sample
clear
use Pseudo4RFS_corp_base_sample_4reg_quarterly_final
keep if rating_scale>10
estpost tabstat ys, statistics(N mean sd p25 p50 p75 ) columns(statistics) listwise   
esttab using corp_sample_sumstat.tex, cells("count(fmt(0))  mean(fmt(2)) sd(fmt(2)) p25(fmt(2)) p50(fmt(2)) p75(fmt(2))") append    
estpost tabstat coupon, statistics(N mean sd p25 p50 p75  ) columns(statistics) listwise   
esttab using corp_sample_sumstat.tex, cells("count(fmt(0))  mean(fmt(2)) sd(fmt(2)) p25(fmt(2)) p50(fmt(2)) p75(fmt(2))") append   
estpost tabstat time2mature, statistics(N mean sd p25 p50 p75 ) columns(statistics) listwise   
esttab using corp_sample_sumstat.tex, cells("count(fmt(0))  mean(fmt(2)) sd(fmt(2)) p25(fmt(2)) p50(fmt(2)) p75(fmt(2))") append   
estpost tabstat age, statistics(N mean sd p25 p50 p75 ) columns(statistics) listwise   
esttab using corp_sample_sumstat.tex, cells("count(fmt(0))  mean(fmt(2)) sd(fmt(2)) p25(fmt(2)) p50(fmt(2)) p75(fmt(2))") append   
estpost tabstat issue_size, statistics(N mean sd p25 p50 p75 ) columns(statistics) listwise   
esttab using corp_sample_sumstat.tex, cells("count(fmt(0))  mean(fmt(2)) sd(fmt(2)) p25(fmt(2)) p50(fmt(2)) p75(fmt(2))") append   
estpost tabstat rating_scale, statistics(N mean sd p25 p50 p75 ) columns(statistics) listwise   
esttab using corp_sample_sumstat.tex, cells("count(fmt(0))  mean(fmt(2)) sd(fmt(2)) p25(fmt(2)) p50(fmt(2)) p75(fmt(2))") append   

	
	
	/*** Table 2 and Figure 1 (first three panels): plots and summary statistics of time series factors   ***/
clear
use Pseudo4RFS_qchange_factors
pwcorr STD_qpctchange_inventory STD_pc_noise_nonlinearLev  STD_qchange_noise  STD_qchange_hkm_nonlinearLev change_vix qpctchange_PFAll, sig

format dt %d
gen yq = qofd(dt)
format yq %tq

twoway (line STD_qpctchange_inventory yq, lp("solid") legend(on) yaxis(1)),  title("") ytitle("", axis(1))  legend(order(1 "{&Delta}Inventory ")) xtitle("") 
      graph export TimeSeries_Plot_InventoryPar.pdf, replace	  
		  
twoway (line STD_pc_noise_nonlinearLev yq, lp("solid") legend(on) yaxis(1)),  title("") ytitle("", axis(1))  legend(order(1 "{&Delta}Distress ")) xtitle("") 
      graph export TimeSeries_Plot_Distress.pdf, replace	  
	  
twoway                                                                                ///
	  (line STD_qchange_noise yq, lp("solide") yaxis(1))     ///
	  (line STD_qchange_hkm_nonlinearLev yq, lpattern("dash") yaxis(1)) ///
	  , legend(order(1 "{&Delta}Noise" 2 "{&Delta}NLev{sup:HKM}") )  title("") ytitle("", axis(1)) ytitle("", axis(1)) xtitle("") 
      graph export TimeSeries_Plot_Noise_Leverage.pdf, replace	  
	
	
	

	
        /*** Table 3 Panel A (CGM regressions): cusip-by-cusip CGM time series regressions: 1-quarter change     ***/
clear
use Pseudo4RFS_corp_base_sample_4reg_quarterly_final
replace yschange=yschange*90        /* yschange is the change of credit spread in percentage scaled to a 90-day period */

gen gp_maturity=1*(time2mature<=5)+2*(time2mature>5 & time2mature<=8)+ 3*(time2mature>8)
gen gp_rating=1*(rating_scale<=4)+2*(rating_scale>4 & rating_scale<=7)+ 3*(rating_scale>7 & rating_scale<=10)+4*(rating_scale>10 & rating_scale<=13)+5*(rating_scale>13)
egen lev_p17=pctile(avg_leverage), p(17)
egen lev_p34=pctile(avg_leverage), p(34)
egen lev_p51=pctile(avg_leverage), p(51)
egen lev_p68=pctile(avg_leverage), p(68)
egen lev_p85=pctile(avg_leverage), p(85)

xtset issue_id yyyyqq 	
egen cusip_group = group(cusip_id)
su cusip_group, meanonly
gen res=.
gen rsqured=.
gen b_lev=.
gen b_jump=.
gen b_sveny10=.
gen b_sveny10squared=.
gen b_slope=.
gen b_sp=.
gen b_vix=.
gen b_intercept=.
forvalues i = 1/`r(max)' {
    reg yschange change_firm_leverage  change_vix change_jump change_sveny10 change2_sveny10 change_slope change_sp if cusip_group == `i' 
	
	predict temp, residuals
	replace res=temp if cusip_group == `i' 
	drop temp
	
	replace rsqured = e(r2_a) if cusip_group == `i' 
	replace b_intercept = _b[_cons] if cusip_group == `i' 
	replace b_vix = _b[change_vix] if cusip_group == `i' 
	replace b_lev = _b[change_firm_leverage] if cusip_group == `i' 
	replace b_jump = _b[change_jump] if cusip_group == `i' 
	replace b_sveny10 = _b[change_sveny10] if cusip_group == `i' 
	replace b_sveny10squared = _b[change2_sveny10] if cusip_group == `i' 
	replace b_slope = _b[change_slope] if cusip_group == `i' 
	replace b_sp = _b[change_sp] if cusip_group == `i' 
 }

      * Generate Table 3 Panel A: bond-level regressions based on rating*maturity groups: 1-quarter change controlling for leverage
egen gpratingMatu=group(gp_maturity gp_rating )
egen total_bonds=nvals(cusip_id)
egen n_bonds_lev=nvals(cusip_id), by(gpratingMatu)
bysort gpratingMatu: gen n_obs_lev=_N
bysort gpratingMatu: egen adjr2_avg=mean(rsqured)
bysort gpratingMatu: egen adjr2_median=median(rsqured)
bysort gpratingMatu: egen b_intercept_avg=mean(b_intercept)
bysort gpratingMatu: egen b_lev_avg=mean(b_lev)
bysort gpratingMatu: egen b_vix_avg=mean(b_vix)
bysort gpratingMatu: egen b_jump_avg=mean(b_jump)
bysort gpratingMatu: egen b_sveny10_avg=mean(b_sveny10)
bysort gpratingMatu: egen b_sveny10squared_avg=mean(b_sveny10squared)
bysort gpratingMatu: egen b_slope_avg=mean(b_slope)
bysort gpratingMatu: egen b_sp_avg=mean(b_sp)
bysort gpratingMatu: egen b_intercept_std=sd(b_intercept)
bysort gpratingMatu: egen b_lev_std=sd(b_lev)
bysort gpratingMatu: egen b_vix_std=sd(b_vix)
bysort gpratingMatu: egen b_jump_std=sd(b_jump)
bysort gpratingMatu: egen b_sveny10_std=sd(b_sveny10)
bysort gpratingMatu: egen b_sveny10squared_std=sd(b_sveny10squared)
bysort gpratingMatu: egen b_slope_std=sd(b_slope)
bysort gpratingMatu: egen b_sp_std=sd(b_sp)
bysort gpratingMatu: gen b_intercept_tstat=sqrt(n_bonds_lev)*b_intercept_avg/b_intercept_std
bysort gpratingMatu: gen b_lev_tstat=sqrt(n_bonds_lev)*b_lev_avg/b_lev_std
bysort gpratingMatu: gen b_vix_tstat=sqrt(n_bonds_lev)*b_vix_avg/b_vix_std
bysort gpratingMatu: gen b_jump_tstat=sqrt(n_bonds_lev)*b_jump_avg/b_jump_std
bysort gpratingMatu: gen b_sveny10_tstat=sqrt(n_bonds_lev)*b_sveny10_avg/b_sveny10_std
bysort gpratingMatu: gen b_sveny10squared_tstat=sqrt(n_bonds_lev)*b_sveny10squared_avg/b_sveny10squared_std
bysort gpratingMatu: gen b_slope_tstat=sqrt(n_bonds_lev)*b_slope_avg/b_slope_std
bysort gpratingMatu: gen b_sp_tstat=sqrt(n_bonds_lev)*b_sp_avg/b_slope_std
collapse (last) adjr2_avg adjr2_median b_intercept_avg b_lev_avg b_vix_avg b_jump_avg b_sveny10_avg b_sveny10squared_avg b_slope_avg b_sp_avg b_intercept_tstat b_lev_tstat b_vix_tstat b_jump_tstat b_sveny10_tstat b_sveny10squared_tstat b_slope_tstat b_sp_tstat n_bonds_lev n_obs_lev total_bonds,  by(gpratingMatu)
outsheet using cusip_level_reg_control_leverage_vix_rating.csv, comma replace    /* this csv file contains the CGM regression results in Table 3  */
    
	
	
	  /*** Table 3 Panel B, Table 4, and Figure 1 (last panel): PC analysis and time series regressiosn of residuals for rating*maturity groups: 1-quarter change controlling for firm leverage   ***/
clear 
use Pseudo4RFS_cusip_level_reg_control_leverage_vix_final    /* this data set contains CGM regression residuals and intermediary factors */
egen gpratingMatu=group(gp_maturity gp_rating )
collapse (mean) res pctchange_inventory, by(gpratingMatu yyyyqq) 
reshape wide res pctchange_inventory, i(yyyyqq)  j(gpratingMatu)  
merge 1:1 yyyyqq using Pseudo4RFS_qchange_factors
egen pctchange_inventory=rowmean(pctchange_inventory*)
egen STD_pctchange_inventory=std(pctchange_inventory)
tostring yyyyqq, replace
gen yyyy=substr(yyyyqq,1,4)
gen qq=substr(yyyyqq,5,2)
destring yyyyqq yyyy qq, replace
gen yq=yq(yyyy,qq)
format yq %tq	 
	 
pca res*, cov 
predict pc1 pc2 pc3 pc4 pc5 , score
corr pc1 pc2 STD_pctchange_inventory pc_noise_nonlinearLev  /* This PCA analysis generates results in Panel B of Table 3 */
 
replace pc1=pc1*90/100 
twoway (line pc1 yq, lp("solid") legend(on) yaxis(1)),  title("") ytitle("percent", axis(1))  legend(order(1 "PC1")) xtitle("") 
      graph export TimeSeries_Plot_PC1.pdf, replace	        /* This is the last panel of Figure 1 */
	  
	    * The following regressions generate Table 4 
foreach r of varlist res*   {
  replace `r'=`r'*90/100     /* quarter-change in percentage */
}
tsset yyyyqq 
ivreg2 res1 STD_pctchange_inventory , bw(auto)   robust
outreg2 using reg_residual, keep(STD_pctchange_inventory STD_pc_noise_nonlinearLev) stats(coef tstat) e(yy mss rss) tex excel nolabel dec(3) coefastr replace
foreach r of varlist res*{
ivreg2 `r'  STD_pctchange_inventory, bw(auto) robust
outreg2 using reg_residual, keep(STD_pctchange_inventory STD_pc_noise_nonlinearLev) e(yy mss rss) stats(coef tstat) tex excel nolabel dec(3) coefastr append
}		
foreach r of varlist res* {
ivreg2 `r' STD_pc_noise_nonlinearLev , bw(auto) robust
outreg2 using reg_residual, keep(STD_pctchange_inventory STD_pc_noise_nonlinearLev) stats(coef tstat) e(yy mss rss) tex excel nolabel dec(3) coefastr append
}	
foreach r of varlist res*{
ivreg2 `r'  STD_pctchange_inventory STD_pc_noise_nonlinearLev, bw(auto) robust
outreg2 using reg_residual, keep(STD_pctchange_inventory STD_pc_noise_nonlinearLev) e(yy mss rss) stats(coef tstat) tex excel nolabel dec(3) coefastr append
}	  /* FVE is calculated based on yy, mss, and rss*/






    /*** Table 5: PC analysis and time series regressiosn of residuals for (rating*volume terciple) groups groups: 1-quarter change controlling for leverage   ***/
clear 
use Pseudo4RFS_cusip_level_reg_control_leverage_vix_final
egen gpRatingVolume=group(gp_rating volume_tgp)	
collapse (mean) res pctchange_inventory, by(gpRatingVolume yyyyqq) 
reshape wide res pctchange_inventory, i(yyyyqq)  j(gpRatingVolume)  
merge 1:1 yyyyqq using Pseudo4RFS_qchange_factors
egen pctchange_inventory=rowmean(pctchange_inventory*)
egen STD_pctchange_inventory=std(pctchange_inventory)
tostring yyyyqq, replace
gen yyyy=substr(yyyyqq,1,4)
gen qq=substr(yyyyqq,5,2)
destring yyyyqq yyyy qq, replace
gen yq=yq(yyyy,qq)
format yq %tq	 
pca res*, cov 
predict pc1 pc2 pc3 pc4 pc5 , score
foreach r of varlist res*   {
  replace `r'=`r'*90/100     /* quarter-change in percentage */
}
tsset yyyyqq
ivreg2 res1 STD_pctchange_inventory STD_pc_noise_nonlinearLev, bw(auto) robust
outreg2 using reg_residual, keep(STD_pctchange_inventory STD_pc_noise_nonlinearLev) stats(coef tstat) e(yy mss rss) tex excel nolabel dec(3) coefastr replace
foreach r of varlist res*{
ivreg2 `r'  STD_pctchange_inventory STD_pc_noise_nonlinearLev, bw(auto) robust
outreg2 using reg_residual, keep(STD_pctchange_inventory STD_pc_noise_nonlinearLev) e(yy mss rss) stats(coef tstat) tex excel nolabel dec(3) coefastr append
}	   /* This generates Panel B of Table 5 */
  
		 * Summary statistics of average trading volume across tercile groups  
clear
use Pseudo4RFS_cusip_level_reg_control_leverage_vix_final
egen gpRatingVolume=group(gp_rating volume_tgp)                  /* volume_tgp is the indicator of the tercile grouops based on the end-of-quarter month's total trading volume of a bond */
bysort gpRatingVolume: egen avg_volume=mean(MonthTotalVolume)    /* avg_volume = the average of the end-of-quarter month's total trading volume acorss bond*quarter for each group based on independent sorting by rating and end-of-quarter month's total trading volume   */
replace avg_volume=avg_volume/1.00e+06                           /* in millions of dollars*/
bysort gpRatingVolume: egen nBond=nvals(cusip_id) 
bysort gpRatingVolume: gen nObs=[_N] 
collapse (last) avg_volume nBond nObs, by(gpRatingVolume)
outsheet using summary_RatingVolume_groups.csv, comma replace    /* This generate Panel A of Table 5 */






      /*** Table 6:  Alternative risk measures to credit rating    ***/
clear 
use Pseudo4RFS_cusip_level_reg_control_leverage_vix_riskmeausre     /* this data set difers from "cusip_level_reg_control_leverage_vix_final.dta" in that it includes betas estimated using univariate regressions  */
          * the followint two lines are alternated to get Panels A and B
egen gp_beta = xtile(b_sp),  n(5)      /* This is from the CGM regression; sign is switched to make the beta=Cov[bond return, market]     */
egen gp_beta = xtile(b_vix),  n(5)     /* This is from the CGM regression: sign is switched to make the beta=Cov[bond return, VIX change] */

egen gpSort=group(gp_maturity gp_beta)	
collapse (mean) res pctchange_inventory, by(gpSort yyyyqq) 
reshape wide res pctchange_inventory, i(yyyyqq)  j(gpSort)  
merge 1:1 yyyyqq using Pseudo4RFS_qchange_factors
egen pctchange_inventory=rowmean(pctchange_inventory*)
egen STD_pctchange_inventory=std(pctchange_inventory)
tostring yyyyqq, replace
gen yyyy=substr(yyyyqq,1,4)
gen qq=substr(yyyyqq,5,2)
destring yyyyqq yyyy qq, replace
gen yq=yq(yyyy,qq)
format yq %tq	 
pca res*, cov 
predict pc1 pc2 pc3 pc4 pc5 , score
foreach r of varlist res*   {
  replace `r'=`r'*90/100     /* quarter-change in percentage */
}
tsset yyyyqq
ivreg2 res1 STD_pctchange_inventory STD_pc_noise_nonlinearLev, bw(auto) robust
outreg2 using reg_residual, keep(STD_pctchange_inventory STD_pc_noise_nonlinearLev) stats(coef tstat) e(yy mss rss) tex excel nolabel dec(3) coefastr replace
foreach r of varlist res*{
ivreg2 `r'  STD_pctchange_inventory STD_pc_noise_nonlinearLev, bw(auto) robust
outreg2 using reg_residual, keep(STD_pctchange_inventory STD_pc_noise_nonlinearLev) e(yy mss rss) stats(coef tstat) tex excel nolabel dec(3) coefastr append
}	
          * summary of beta groups (the first column in each panel of Table 6)
clear 
use Pseudo4RFS_cusip_level_reg_control_leverage_vix_riskmeausre
egen gp_beta = xtile(b_sp),  n(5)      
egen gpSort=group(gp_maturity gp_beta)	
bysort gpSort: egen avg_beta=mean(b_sp)
bysort gpSort: egen nBond=nvals(cusip_id) 
bysort gpSort: gen nObs=[_N] 
collapse (last) avg_beta nBond nObs, by(gpSort)
outsheet using summary_beta_groups.csv, comma replace    /* for Panel A*/

clear 
use Pseudo4RFS_cusip_level_reg_control_leverage_vix_riskmeausre   
egen gp_beta = xtile(b_vix),  n(5)     
egen gpSort=group(gp_maturity gp_beta)	
bysort gpSort: egen avg_beta=mean(b_vix)
bysort gpSort: egen nBond=nvals(cusip_id) 
bysort gpSort: gen nObs=[_N] 
collapse (last) avg_beta nBond nObs, by(gpSort)
outsheet using summary_beta_groups.csv, comma replace    /* for Panel B*/







     /*** Table 7: HY vs IG bond  ***/
clear 
use Pseudo4RFS_cusip_level_reg_control_leverage
replace gp_rating=6 if gp_rating==7
replace gp_rating=2 if gp_rating==1
egen gpratingMatu=group(gp_maturity gp_rating )
collapse (mean) res change_inventory change_inventory_HY change_inventory_IG , by(gpratingMatu yyyyqq) 
reshape wide res change_inventory change_inventory_HY change_inventory_IG, i(yyyyqq)  j(gpratingMatu)  
egen change_inventory=rowmean(change_inventory*)
egen change_inventory_HY=rowmean(change_inventory_HY*)
gen change_inventory_IG=change_inventory-change_inventory_HY
merge 1:1 yyyyqq using Pseudo4RFS_qchange_factors
pca res*, cov 
predict pc1 pc2 pc3 pc4 pc5 , score 
foreach r of varlist res*   {
  replace `r'=`r'*90/100     /* quarter-change in percentage */
}
egen STD_change_inventoryHY=std(change_inventory_HY)
egen STD_change_inventoryIG=std(change_inventory_IG)
tsset yyyyqq 
ivreg2 res1 STD_change_inventoryHY STD_pc_noise_nonlinearLev, bw(auto) robust
outreg2 using reg_residual_HYIG, keep(STD_change_inventoryHY STD_pc_noise_nonlinearLev) stats(coef tstat) e(yy mss rss) tex excel nolabel dec(3) coefastr replace
foreach r of varlist res*{
ivreg2 `r'   STD_change_inventoryHY STD_pc_noise_nonlinearLev, bw(auto) robust
outreg2 using reg_residual_HYIG, keep(STD_change_inventoryHY STD_pc_noise_nonlinearLev) e(yy mss rss) stats(coef tstat) tex excel nolabel dec(3) coefastr append
}	
foreach r of varlist res*{
ivreg2 `r'   STD_change_inventoryIG STD_pc_noise_nonlinearLev, bw(auto) robust
outreg2 using reg_residual_HYIG, keep(STD_change_inventoryIG STD_pc_noise_nonlinearLev) e(yy mss rss) stats(coef tstat) tex excel nolabel dec(3) coefastr append
}
corr  STD_change_inventoryHY STD_change_inventoryIG



		 
		 
		 
  /***  Table 8 and Table A.4 (Panel A): Quarterly regressions of agency MBS OAS changes on inventory measures   ***/
clear
use Pseudo4RFS_agencyMBS                                    /* Last-day-of-month series in units of BPs */
    * merge with the Tsy yield data 
merge 1:1 trddate_num using tsy  
drop if _merge==2  
drop _merge
     * merge with the SP500 jump factor
merge 1:1 yyyymm using jump_sp500  
drop if _merge==2  
drop _merge
    * merge with the aggreagte vix seires
merge 1:1 trddate_num using vixclose_daily  
drop if _merge==2  
drop _merge
    * merge with the HPW noise series
merge 1:1 trddate_num using Noise_Measure_daily  
drop if _merge==2  
drop _merge
    * merge with the HKM intermediary constraint measures
merge 1:1 yyyymm using He_Kelly_Manela_Factors_monthly 
drop if _merge==2  
drop _merge
    * merge with the S&P 500 index seires
merge 1:1 trddate_num using SP_index  
drop if _merge==2  
drop _merge

gen qq=quarter(trd_dt)
gen yyyyqq=yyyy*100+qq
sort yyyymm
bysort yyyyqq: gen ord=[_n]
drop if ord~=3                       /* Last-month-of-quarter series  */

replace fnclccccliboroas=fnclccccliboroas/100   /*  rescale form BP to percent */
replace fnciccccliboroas=fnciccccliboroas/100
replace fglmcccccliboroas=fglmcccccliboroas/100
replace fgciccccliboroas=fgciccccliboroas/100
gen change_sveny10=sveny10[_n]-sveny10[_n-1]
gen change2_sveny10=(sveny10[_n]-sveny10[_n-1])^2
gen change_slope=tsy_slope[_n]-tsy_slope[_n-1]
gen change_vix=vixclose[_n]-vixclose[_n-1]
gen change_noise=noise_bp[_n]-noise_bp[_n-1]
gen change_intermediary=intermediary_leverage_ratio_squa[_n]-intermediary_leverage_ratio_squa[_n-1]
gen change_sp=log(spindx[_n])-log(spindx[_n-1])
gen change_fncl=fnclccccliboroas[_n]-fnclccccliboroas[_n-1]     /* 1-quarter change */
gen change_fnci=fnciccccliboroas[_n]-fnciccccliboroas[_n-1]
gen change_fglm=fglmcccccliboroas[_n]-fglmcccccliboroas[_n-1]
gen change_fgci=fgciccccliboroas[_n]-fgciccccliboroas[_n-1]
tsset yyyyqq
merge 1:1 yyyyqq using Pseudo4RFS_qchange_factors
drop if (yyyyqq<200501 |  yyyyqq>201502)              /* This makes the sample period 2005:Q1 - 2015:Q2 */

     *** Table A.4 (Panel A) summary statistics 
estpost tabstat fnclccccliboroas, statistics(N mean sd  p25 p50 p75 ) columns(statistics) listwise   
esttab using AgencyMBSSummary.tex, cells("count(fmt(0))  mean(fmt(3)) sd(fmt(3))  p25(fmt(3)) p50(fmt(3)) p75(fmt(3))  ") replace    
estpost tabstat fnciccccliboroas, statistics(N mean sd  p25 p50 p75 ) columns(statistics) listwise   
esttab using AgencyMBSSummary.tex, cells("count(fmt(0))  mean(fmt(3)) sd(fmt(3))  p25(fmt(3)) p50(fmt(3)) p75(fmt(3))  ") append   
estpost tabstat fglmcccccliboroas, statistics(N mean sd  p25 p50 p75 ) columns(statistics) listwise   
esttab using AgencyMBSSummary.tex, cells("count(fmt(0))  mean(fmt(3)) sd(fmt(3))  p25(fmt(3)) p50(fmt(3)) p75(fmt(3))  ") append   
estpost tabstat fgciccccliboroas, statistics(N mean sd  p25 p50 p75 ) columns(statistics) listwise   
esttab using AgencyMBSSummary.tex, cells("count(fmt(0))  mean(fmt(3)) sd(fmt(3))  p25(fmt(3)) p50(fmt(3)) p75(fmt(3))  ") append   

     *** Table 8 (Panel A) regressions
egen STD_qpctchange_inventory=std(qpctchange_inventoryPar)
regress change_fncl   change_vix change_jump sveny10 change2_sveny10 tsy_slope change_sp
predict res_fncl, residuals
regress change_fnci    change_vix change_jump sveny10 change2_sveny10 tsy_slope change_sp
predict res_fnci, residuals
regress change_fglm    change_vix change_jump sveny10 change2_sveny10 tsy_slope change_sp
predict res_fglm, residuals
regress change_fgci   change_vix change_jump sveny10 change2_sveny10 tsy_slope change_sp
predict res_fgci, residuals

ivreg2 res_fncl STD_qpctchange_inventory , bw(auto) robust
outreg2 using reg_oas, keep(STD_qpctchange_inventory STD_pc_noise_nonlinearLev ) stats(coef tstat) tex excel nolabel dec(3) coefastr replace	
foreach r in res_fncl res_fnci res_fglm res_fgci   {
ivreg2 `r' STD_qpctchange_inventory STD_pc_noise_nonlinearLev,  bw(auto) robust
outreg2 using reg_oas, keep(STD_qpctchange_inventory STD_pc_noise_nonlinearLev) stats(coef tstat) tex excel nolabel dec(3) coefastr append
}	




    /*** Table 8 and Table A.4 (Panel B): Quarterly regressions of non-Agency CMBS spreads (relative to Tsy) changes on inventory measures ***/
clear
use Pseudo4RFS_BaclaysNonAgencyMBS                             /* Last-week-of-month series in BPs*/
    * merge with the Tsy yield data 
merge 1:1 trddate_num using tsy  
drop if _merge==2  
drop _merge
     * merge with the SP500 jump factor
merge 1:1 yyyymm using jump_sp500  
drop if _merge==2  
drop _merge
    * merge with the aggreagte vix seires
merge 1:1 trddate_num using vixclose_daily  
drop if _merge==2  
drop _merge
    * merge with the HPW noise series
merge 1:1 trddate_num using Noise_Measure_daily  
drop if _merge==2  
drop _merge
    * merge with the HKM intermediary constraint measures
merge 1:1 yyyymm using He_Kelly_Manela_Factors_monthly 
drop if _merge==2  
drop _merge
    * merge with the S&P 500 index seires
merge 1:1 trddate_num using SP_index  
drop if _merge==2  
drop _merge

gen qq=quarter(trd_dt)
gen yyyyqq=yyyy*100+qq
sort yyyymm
bysort yyyyqq: gen ord=[_n]
drop if ord~=3                         /* Last-week-of-quarter series  */

replace cmbs05Duper=cmbs05Duper/100     /* in percentage points  */
replace cmbs05AM=cmbs05AM/100           /* in percentage points  */
replace cmbs05AJ=cmbs05AJ/100           /* in percentage points  */
gen change_sveny10=sveny10[_n]-sveny10[_n-1]
gen change2_sveny10=(sveny10[_n]-sveny10[_n-1])^2
gen change_slope=tsy_slope[_n]-tsy_slope[_n-1]
gen change_vix=vixclose[_n]-vixclose[_n-1]
gen change_noise=noise_bp[_n]-noise_bp[_n-1]
gen change_intermediary=intermediary_leverage_ratio_squa[_n]-intermediary_leverage_ratio_squa[_n-1]
gen change_sp=log(spindx[_n])-log(spindx[_n-1])
gen change_cmbs05Duper=cmbs05Duper[_n]-cmbs05Duper[_n-1]   /*1-quarter change*/
gen change_cmbs05AM=cmbs05AM[_n]-cmbs05AM[_n-1]
gen change_cmbs05AJ=cmbs05AJ[_n]-cmbs05AJ[_n-1]

drop if (yyyyqq<200501 | yyyyqq>201502)            /* This makes the sample period 2005:Q4 - 2015:Q2 */
gen yq = qofd(trd_dt)
format yq %tq
merge 1:1 yyyyqq using Pseudo4RFS_qchange_factors
egen STD_qpctchange_inventory=std(qpctchange_inventoryPar)
tsset yyyyqq

regress change_cmbs05Duper  change_vix change_jump sveny10 change2_sveny10 tsy_slope change_sp
predict res_cmbs05Duper, residuals
regress change_cmbs05AM   change_vix change_jump sveny10 change2_sveny10 tsy_slope change_sp
predict res_cmbs05AM, residuals
regress change_cmbs05AJ   change_vix change_jump sveny10 change2_sveny10 tsy_slope change_sp 
predict res_cmbs05AJ, residuals

    * Table 8 (Panel B) regressions
ivreg2 change_cmbs05Duper STD_qpctchange_inventory, bw(auto) robust
outreg2 using reg_cmbs, keep(STD_qpctchange_inventory STD_pc_noise_nonlinearLev ) stats(coef tstat) tex excel nolabel dec(3) coefastr replace
foreach r in res_cmbs05Duper res_cmbs05AM res_cmbs05AJ {
ivreg2 `r' STD_qpctchange_inventory STD_pc_noise_nonlinearLev,  bw(auto) robust
outreg2 using reg_cmbs, keep(STD_qpctchange_inventory STD_pc_noise_nonlinearLev) stats(coef tstat) tex excel nolabel dec(3) coefastr append
}	
     * Table A.4 (Panel B) summary statistics
estpost tabstat cmbs05Duper, statistics(N mean sd  p25 p50 p75 ) columns(statistics) listwise   
esttab using CMBSSummary.tex, cells("count(fmt(0))  mean(fmt(3)) sd(fmt(3))  p25(fmt(3)) p50(fmt(3)) p75(fmt(3))  ") replace    
estpost tabstat cmbs05AM, statistics(N mean sd  p25 p50 p75 ) columns(statistics) listwise   
esttab using CMBSSummary.tex, cells("count(fmt(0))  mean(fmt(3)) sd(fmt(3))  p25(fmt(3)) p50(fmt(3)) p75(fmt(3))  ") append   
estpost tabstat cmbs05AJ, statistics(N mean sd  p25 p50 p75 ) columns(statistics) listwise   
esttab using CMBSSummary.tex, cells("count(fmt(0))  mean(fmt(3)) sd(fmt(3))  p25(fmt(3)) p50(fmt(3)) p75(fmt(3))")   append   





    /*** Table 8 and Table A.4 (Panel C): Quarterly regressions of ABS spreads (relative to Tsy) changes on inventory measures   ***/
clear
use Pseudo4RFS_BaclaysABS                                     /* Last-week-of-month series in BPs*/
    * merge with the Tsy yield data 
merge 1:1 trddate_num using tsy  
drop if _merge==2  
drop _merge
     * merge with the SP500 jump factor
merge 1:1 yyyymm using jump_sp500  
drop if _merge==2  
drop _merge
    * merge with the aggreagte vix seires
merge 1:1 trddate_num using vixclose_daily  
drop if _merge==2  
drop _merge
    * merge with the HPW noise series
merge 1:1 trddate_num using Noise_Measure_daily  
drop if _merge==2  
drop _merge
    * merge with the HKM intermediary constraint measures
merge 1:1 yyyymm using He_Kelly_Manela_Factors_monthly 
drop if _merge==2  
drop _merge
    * merge with the S&P 500 index seires
merge 1:1 trddate_num using SP_index  
drop if _merge==2  
drop _merge

gen qq=quarter(trd_dt)
gen yyyyqq=yyyy*100+qq
sort yyyymm
bysort yyyyqq: gen ord=[_n]
drop if ord~=3                                  /* Last-week-of-quarter series  */

replace ccfixedaaa5yr=ccfixedaaa5yr/100     /* in percentage points  */
replace primeautofixedaaa3yr=primeautofixedaaa3yr/100     /* in percentage points  */
replace primeautofixeda3yr=primeautofixeda3yr/100     /* in percentage points  */
replace primeautofixedbbb3yr=primeautofixedbbb3yr/100     /* in percentage points  */
gen change_sveny10=sveny10[_n]-sveny10[_n-1]
gen change2_sveny10=(sveny10[_n]-sveny10[_n-1])^2
gen change_slope=tsy_slope[_n]-tsy_slope[_n-1]
gen change_vix=vixclose[_n]-vixclose[_n-1]
gen change_noise=noise_bp[_n]-noise_bp[_n-1]
gen change_intermediary=intermediary_leverage_ratio_squa[_n]-intermediary_leverage_ratio_squa[_n-1]
gen change_sp=log(spindx[_n])-log(spindx[_n-1])
replace primeautofixedbbb3yr=. if primeautofixedbbb3yr<=0	  
replace primeautofixeda3yr=. if primeautofixeda3yr<=0	  
replace primeautofixedaaa3yr=. if primeautofixedaaa3yr<=0	  

gen yq = qofd(trd_dt)
format yq %tq
gen change_CC=ccfixedaaa5yr[_n]-ccfixedaaa5yr[_n-1]     /* 1-quarter change */
gen change_AutoAAA=primeautofixedaaa3yr[_n]-primeautofixedaaa3yr[_n-1]
gen change_AutoA=primeautofixeda3yr[_n]-primeautofixeda3yr[_n-1]
gen change_AutoBBB=primeautofixedbbb3yr[_n]-primeautofixedbbb3yr[_n-1]
merge 1:1 yyyyqq using Pseudo4RFS_qchange_factors
drop if (yyyyqq<200501 | yyyyqq>201502)  
egen STD_qpctchange_inventory=std(qpctchange_inventoryPar)

      * Table A.4 (Panel C) summary statistics
estpost tabstat ccfixedaaa5yr, statistics(N mean sd  p25 p50 p75 ) columns(statistics) listwise   
esttab using ABSSummary.tex, cells("count(fmt(0))  mean(fmt(3)) sd(fmt(3))  p25(fmt(3)) p50(fmt(3)) p75(fmt(3))") replace    
estpost tabstat primeautofixedaaa3yr, statistics(N mean sd  p25 p50 p75 ) columns(statistics) listwise   
esttab using ABSSummary.tex, cells("count(fmt(0))  mean(fmt(3)) sd(fmt(3))  p25(fmt(3)) p50(fmt(3)) p75(fmt(3))") append   
estpost tabstat primeautofixeda3yr, statistics(N mean sd  p25 p50 p75 ) columns(statistics) listwise   
esttab using ABSSummary.tex, cells("count(fmt(0))  mean(fmt(3)) sd(fmt(3))  p25(fmt(3)) p50(fmt(3)) p75(fmt(3))") append   
estpost tabstat primeautofixedbbb3yr, statistics(N mean sd  p25 p50 p75 ) columns(statistics) listwise   
esttab using ABSSummary.tex, cells("count(fmt(0))  mean(fmt(3)) sd(fmt(3))  p25(fmt(3)) p50(fmt(3)) p75(fmt(3))") append   

       * Table 8 (Panel C) regressions
tsset yyyyqq
regress change_CC  change_vix change_jump sveny10 change2_sveny10 tsy_slope change_sp
predict res_CC, residuals
regress change_AutoAAA   change_vix change_jump sveny10 change2_sveny10 tsy_slope change_sp
predict res_AutoAAA, residuals
regress change_AutoA   change_vix change_jump sveny10 change2_sveny10 tsy_slope change_sp 
predict res_AutoA, residuals
regress change_AutoBBB change_vix change_jump sveny10 change2_sveny10 tsy_slope change_sp
predict res_AutoBBB, residuals

ivreg2 res_CC STD_qpctchange_inventory , bw(auto) robust
outreg2 using reg_ABS, keep(STD_qpctchange_inventory STD_pc_noise_nonlinearLev ) stats(coef tstat) tex excel nolabel dec(3) coefastr replace	
foreach r in res_CC  res_AutoAAA change_AutoA change_AutoBBB   {
ivreg2 `r' STD_qpctchange_inventory STD_pc_noise_nonlinearLev,  bw(auto) robust
outreg2 using reg_ABS, keep(STD_qpctchange_inventory STD_pc_noise_nonlinearLev) stats(coef tstat) tex excel nolabel dec(3) coefastr append
}	






     /*** Table 8 and Table A.4 (Panel D):  Monthly regressions of S&P 500 index option returns   ****/
clear
import delimited DataThePuzzleOfOptionReturns_60d     /* monthly series of gross returns (1.0050 means 0.5% monthly returns and annualized 6% return)  */
    * merge with the Tsy yield data 
merge 1:1 yyyymm using tsy_monthly  
drop if _merge==2  
drop _merge
     * merge with the SP500 jump factor
merge 1:1 yyyymm using jump_sp500  
drop if _merge==2  
drop _merge
    * merge with the aggreagte vix seires
merge 1:1 yyyymm using vixclose_monthly  
drop if _merge==2  
drop _merge
    * merge with the HPW noise series
merge 1:1 yyyymm using noise_monthly  
drop if _merge==2  
drop _merge
    * merge with the HKM intermediary constraint measures
merge 1:1 yyyymm using He_Kelly_Manela_Factors_monthly 
drop if _merge==2  
drop _merge
    * merge with the S&P 500 index seires
merge 1:1 yyyymm using SP_index_monthly  
drop if _merge==2  
drop _merge

gen change_sveny10=sveny10[_n]-sveny10[_n-1]
gen change2_sveny10=(sveny10[_n]-sveny10[_n-1])^2
gen change_slope=tsy_slope[_n]-tsy_slope[_n-1]
gen change_vix=vixclose[_n]-vixclose[_n-1]
gen change_noise=noise_bp[_n]-noise_bp[_n-1]
gen change_intermediary=intermediary_leverage_ratio_squa[_n]-intermediary_leverage_ratio_squa[_n-1]
gen intermediary_lev_ratio=1/intermediary_capital_ratio
gen change_hkm_lev_ratio=intermediary_lev_ratio[_n]-intermediary_lev_ratio[_n-1]
gen change_hkm_interact=(intermediary_lev_ratio[_n])^2-(intermediary_lev_ratio[_n-1])^2
gen change_sp=log(spindx[_n])-log(spindx[_n-1])

merge 1:1 yyyymm using Pseudo4RFS_mchange_factors
drop if (yyyymm<200501 |  call_30_925==. | yyyymm>201201)           /* This makes the sample period 1/2005 - 1/2012  */
tsset yyyymm

drop call_30_925 call_30_975 call_30_1025 call_30_1075 put_30925 put_30975 put_301025 put_301075
foreach r in call_30_90 call_30_95  call_30_100 call_30_105 call_30_110 {
replace `r'=(`r'-1)*100           /* net (unannalized) monthly return in percentage points   */
}	
foreach r in put_30_90 put_3095 put_30100 put_30105 put_30110{
replace `r'=-(`r'-1)*100             /* net (unannalized) monthly return in percentage points, and take the negative value    */
}	

    *** Table 8 (Panel D) regressions
pca change_noise change_hkm_interact 
predict pc_noise_HKMinteract , score	 
egen STD_mpctchange_inventory=std(mpctchange_inventory)
egen STD_pc_noise_nonlinearLev=std(pc_noise_HKMinteract)

regress call_30_90   change_vix change_jump sveny10 change2_sveny10 tsy_slope change_sp
predict res_call_30_90, residuals
regress call_30_95    change_vix change_jump sveny10 change2_sveny10 tsy_slope change_sp
predict res_call_30_95, residuals
regress call_30_100    change_vix change_jump sveny10 change2_sveny10 tsy_slope change_sp
predict res_call_30_100, residuals
regress call_30_105   change_vix change_jump sveny10 change2_sveny10 tsy_slope change_sp
predict res_call_30_105, residuals
regress call_30_110   change_vix change_jump sveny10 change2_sveny10 tsy_slope change_sp
predict res_call_30_110, residuals

regress put_30_90  change_vix change_jump sveny10 change2_sveny10 tsy_slope change_sp
predict res_put_30_90, residuals
regress put_3095   change_vix change_jump sveny10 change2_sveny10 tsy_slope change_sp
predict res_put_3095, residuals
regress put_30100   change_vix change_jump sveny10 change2_sveny10 tsy_slope change_sp
predict res_put_30100, residuals
regress put_30105  change_vix change_jump sveny10 change2_sveny10 tsy_slope change_sp
predict res_put_30105, residuals
regress put_30110   change_vix change_jump  sveny10 change2_sveny10 tsy_slope change_sp
predict res_put_30110, residuals

ivreg2 res_call_30_90 STD_mpctchange_inventory , bw(auto) robust
outreg2 using reg_residual, keep(STD_mpctchange_inventory STD_pc_noise_nonlinearLev) stats(coef tstat) e(yy rss)  tex excel nolabel dec(3) coefastr replace	
foreach r of varlist res* {
ivreg2 `r' STD_mpctchange_inventory STD_pc_noise_nonlinearLev, bw(auto) robust
outreg2 using reg_residual, keep(STD_mpctchange_inventory STD_pc_noise_nonlinearLev) stats(coef tstat) e(yy rss)  tex excel nolabel dec(3) coefastr append
}	

      *** Table A.4 (Panel D) summary statistics
estpost tabstat call_30_90, statistics(N mean sd  p25 p50 p75) columns(statistics) listwise   
esttab using SPOptRetSummary.tex, cells("count(fmt(0))  mean(fmt(3)) sd(fmt(3))  p25(fmt(3)) p50(fmt(3)) p75(fmt(3))") replace    
estpost tabstat call_30_95, statistics(N mean sd  p25 p50 p75 ) columns(statistics) listwise   
esttab using SPOptRetSummary.tex, cells("count(fmt(0))  mean(fmt(3)) sd(fmt(3))  p25(fmt(3)) p50(fmt(3)) p75(fmt(3))") append   
estpost tabstat call_30_100, statistics(N mean sd  p25 p50 p75 ) columns(statistics) listwise   
esttab using SPOptRetSummary.tex, cells("count(fmt(0))  mean(fmt(3)) sd(fmt(3))  p25(fmt(3)) p50(fmt(3)) p75(fmt(3))") append   
estpost tabstat call_30_105, statistics(N mean sd  p25 p50 p75 ) columns(statistics) listwise   
esttab using SPOptRetSummary.tex, cells("count(fmt(0))  mean(fmt(3)) sd(fmt(3))  p25(fmt(3)) p50(fmt(3)) p75(fmt(3))") append   
estpost tabstat call_30_110, statistics(N mean sd  p25 p50 p75 ) columns(statistics) listwise   
esttab using SPOptRetSummary.tex, cells("count(fmt(0))  mean(fmt(3)) sd(fmt(3))  p25(fmt(3)) p50(fmt(3)) p75(fmt(3))") append
estpost tabstat put_30_90, statistics(N mean sd  p25 p50 p75 ) columns(statistics) listwise   
esttab using SPOptRetSummary.tex, cells("count(fmt(0))  mean(fmt(3)) sd(fmt(3))  p25(fmt(3)) p50(fmt(3)) p75(fmt(3))") append    
estpost tabstat put_3095, statistics(N mean sd  p25 p50 p75 ) columns(statistics) listwise   
esttab using SPOptRetSummary.tex, cells("count(fmt(0))  mean(fmt(3)) sd(fmt(3))  p25(fmt(3)) p50(fmt(3)) p75(fmt(3))") append   
estpost tabstat put_30100, statistics(N mean sd  p25 p50 p75 ) columns(statistics) listwise   
esttab using SPOptRetSummary.tex, cells("count(fmt(0))  mean(fmt(3)) sd(fmt(3))  p25(fmt(3)) p50(fmt(3)) p75(fmt(3))") append   
estpost tabstat put_30105, statistics(N mean sd  p25 p50 p75 ) columns(statistics) listwise   
esttab using SPOptRetSummary.tex, cells("count(fmt(0))  mean(fmt(3)) sd(fmt(3))  p25(fmt(3)) p50(fmt(3)) p75(fmt(3))") append   
estpost tabstat put_30110, statistics(N mean sd  p25 p50 p75 ) columns(statistics) listwise   
esttab using SPOptRetSummary.tex, cells("count(fmt(0))  mean(fmt(3)) sd(fmt(3))  p25(fmt(3)) p50(fmt(3)) p75(fmt(3))") append   









    /*** Table 9: summary statistics of holding changes in raw amount (average across a combinaton of yyyyqq*CUSIP)   ***/
	        * Panels A, B, and C
clear 
use Pseudo4RFS_eMAX_regresion_sample   /* the basic structure is: fund_type yyyyqq issue_id  */
keep if ind_DNG==2          /* No Rating Change */
sort fund_type yyyyqq issue_id    
estpost tabstat hold_change_t if fund_type==1, statistics(N mean  sd p25 p50 p75) columns(statistics) listwise   
esttab using FundHolding_sumstat.tex, cells("count(fmt(0))  mean(fmt(3)) sd(fmt(3)) p25(fmt(3)) p50(fmt(3)) p75(fmt(3))") replace  
estpost tabstat hold_change_tPlus1 if fund_type==1, statistics(N mean sd p25 p50 p75) columns(statistics) listwise   
esttab using FundHolding_sumstat.tex, cells("count(fmt(0))  mean(fmt(3)) sd(fmt(3)) p25(fmt(3)) p50(fmt(3)) p75(fmt(3))") append   
estpost tabstat hold_change_t if fund_type==2, statistics(N mean  sd p25 p50 p75) columns(statistics) listwise   
esttab using FundHolding_sumstat.tex, cells("count(fmt(0))  mean(fmt(3)) sd(fmt(3)) p25(fmt(3)) p50(fmt(3)) p75(fmt(3))") append   
estpost tabstat hold_change_tPlus1 if fund_type==2, statistics(N mean sd p25 p50 p75) columns(statistics) listwise   
esttab using FundHolding_sumstat.tex, cells("count(fmt(0))  mean(fmt(3)) sd(fmt(3)) p25(fmt(3)) p50(fmt(3)) p75(fmt(3))") append   
estpost tabstat hold_change_t if fund_type==3, statistics(N mean  sd p25 p50 p75) columns(statistics) listwise   
esttab using FundHolding_sumstat.tex, cells("count(fmt(0))  mean(fmt(3)) sd(fmt(3)) p25(fmt(3)) p50(fmt(3)) p75(fmt(3))") append    
estpost tabstat hold_change_tPlus1 if fund_type==3, statistics(N mean median sd p25 p50 p75) columns(statistics) listwise   
esttab using FundHolding_sumstat.tex, cells("count(fmt(0))  mean(fmt(3)) sd(fmt(3)) p25(fmt(3)) p50(fmt(3)) p75(fmt(3))") append   
estpost tabstat paramt if fund_type==1, statistics(N mean  sd p25 p50 p75) columns(statistics) listwise   
esttab using FundHolding_sumstat.tex,  cells("count(fmt(0))  mean(fmt(3)) sd(fmt(3)) p25(fmt(3)) p50(fmt(3)) p75(fmt(3))") append  
estpost tabstat paramt if fund_type==2, statistics(N mean sd p25 p50 p75) columns(statistics) listwise   
esttab using FundHolding_sumstat.tex,  cells("count(fmt(0))  mean(fmt(3)) sd(fmt(3)) p25(fmt(3)) p50(fmt(3)) p75(fmt(3))") append   
estpost tabstat paramt if fund_type==3, statistics(N mean sd p25 p50 p75) columns(statistics) listwise   
esttab using FundHolding_sumstat.tex,  cells("count(fmt(0))  mean(fmt(3)) sd(fmt(3)) p25(fmt(3)) p50(fmt(3)) p75(fmt(3))") append   

clear 
use Pseudo4RFS_eMAX_regresion_sample
keep if ind_DNG==1   
drop if ind_FallenInHY==1  /* Downgrade (IG): downgrade within IG */
sort fund_type yyyyqq issue_id  
estpost tabstat hold_change_t if fund_type==1, statistics(N mean  sd p25 p50 p75) columns(statistics) listwise   
esttab using FundHolding_sumstat.tex, cells("count(fmt(0))  mean(fmt(3)) sd(fmt(3)) p25(fmt(3)) p50(fmt(3)) p75(fmt(3))") replace   
estpost tabstat hold_change_tPlus1 if fund_type==1, statistics(N mean sd p25 p50 p75) columns(statistics) listwise   
esttab using FundHolding_sumstat.tex, cells("count(fmt(0))  mean(fmt(3)) sd(fmt(3)) p25(fmt(3)) p50(fmt(3)) p75(fmt(3))") append    
estpost tabstat hold_change_t if fund_type==2, statistics(N mean  sd p25 p50 p75) columns(statistics) listwise   
esttab using FundHolding_sumstat.tex, cells("count(fmt(0))  mean(fmt(3)) sd(fmt(3)) p25(fmt(3)) p50(fmt(3)) p75(fmt(3))") append   
estpost tabstat hold_change_tPlus1 if fund_type==2, statistics(N mean sd p25 p50 p75) columns(statistics) listwise   
esttab using FundHolding_sumstat.tex,cells("count(fmt(0))  mean(fmt(3)) sd(fmt(3)) p25(fmt(3)) p50(fmt(3)) p75(fmt(3))") append    
estpost tabstat hold_change_t if fund_type==3, statistics(N mean  sd p25 p50 p75) columns(statistics) listwise   
esttab using FundHolding_sumstat.tex, cells("count(fmt(0))  mean(fmt(3)) sd(fmt(3)) p25(fmt(3)) p50(fmt(3)) p75(fmt(3))") append   
estpost tabstat hold_change_tPlus1 if fund_type==3, statistics(N mean median sd p25 p50 p75) columns(statistics) listwise   
esttab using FundHolding_sumstat.tex, cells("count(fmt(0))  mean(fmt(3)) sd(fmt(3)) p25(fmt(3)) p50(fmt(3)) p75(fmt(3))") append     
estpost tabstat paramt if fund_type==1, statistics(N mean  sd p25 p50 p75) columns(statistics) listwise   
esttab using FundHolding_sumstat.tex,  cells("count(fmt(0))  mean(fmt(3)) sd(fmt(3)) p25(fmt(3)) p50(fmt(3)) p75(fmt(3))") append  
estpost tabstat paramt if fund_type==2, statistics(N mean sd p25 p50 p75) columns(statistics) listwise   
esttab using FundHolding_sumstat.tex,  cells("count(fmt(0))  mean(fmt(3)) sd(fmt(3)) p25(fmt(3)) p50(fmt(3)) p75(fmt(3))") append   
estpost tabstat paramt if fund_type==3, statistics(N mean sd p25 p50 p75) columns(statistics) listwise   
esttab using FundHolding_sumstat.tex,  cells("count(fmt(0))  mean(fmt(3)) sd(fmt(3)) p25(fmt(3)) p50(fmt(3)) p75(fmt(3))") append   

clear 
use Pseudo4RFS_eMAX_regresion_sample
keep if ind_Fallen==1  /* Fallen Angle (downgrade from IG to HY)*/
sort fund_type yyyyqq issue_id    
estpost tabstat hold_change_t if fund_type==1, statistics(N mean  sd p25 p50 p75) columns(statistics) listwise   
esttab using FundHolding_sumstat.tex, cells("count(fmt(0))  mean(fmt(3)) sd(fmt(3)) p25(fmt(3)) p50(fmt(3)) p75(fmt(3))") append   
estpost tabstat hold_change_tPlus1 if fund_type==1, statistics(N mean sd p25 p50 p75) columns(statistics) listwise   
esttab using FundHolding_sumstat.tex, cells("count(fmt(0))  mean(fmt(3)) sd(fmt(3)) p25(fmt(3)) p50(fmt(3)) p75(fmt(3))") append   
estpost tabstat hold_change_t if fund_type==2, statistics(N mean  sd p25 p50 p75) columns(statistics) listwise   
esttab using FundHolding_sumstat.tex, cells("count(fmt(0))  mean(fmt(3)) sd(fmt(3)) p25(fmt(3)) p50(fmt(3)) p75(fmt(3))") append   
estpost tabstat hold_change_tPlus1 if fund_type==2, statistics(N mean sd p25 p50 p75) columns(statistics) listwise   
esttab using FundHolding_sumstat.tex, cells("count(fmt(0))  mean(fmt(3)) sd(fmt(3)) p25(fmt(3)) p50(fmt(3)) p75(fmt(3))") append   
estpost tabstat hold_change_t if fund_type==3, statistics(N mean  sd p25 p50 p75) columns(statistics) listwise   
esttab using FundHolding_sumstat.tex, cells("count(fmt(0))  mean(fmt(3)) sd(fmt(3)) p25(fmt(3)) p50(fmt(3)) p75(fmt(3))") append    
estpost tabstat hold_change_tPlus1 if fund_type==3, statistics(N mean median sd p25 p50 p75) columns(statistics) listwise   
esttab using FundHolding_sumstat.tex, cells("count(fmt(0))  mean(fmt(3)) sd(fmt(3)) p25(fmt(3)) p50(fmt(3)) p75(fmt(3))") append      
estpost tabstat paramt if fund_type==1, statistics(N mean  sd p25 p50 p75) columns(statistics) listwise   
esttab using FundHolding_sumstat.tex,  cells("count(fmt(0))  mean(fmt(3)) sd(fmt(3)) p25(fmt(3)) p50(fmt(3)) p75(fmt(3))") append  
estpost tabstat paramt if fund_type==2, statistics(N mean sd p25 p50 p75) columns(statistics) listwise   
esttab using FundHolding_sumstat.tex,  cells("count(fmt(0))  mean(fmt(3)) sd(fmt(3)) p25(fmt(3)) p50(fmt(3)) p75(fmt(3))") append   
estpost tabstat paramt if fund_type==3, statistics(N mean sd p25 p50 p75) columns(statistics) listwise   
esttab using FundHolding_sumstat.tex,  cells("count(fmt(0))  mean(fmt(3)) sd(fmt(3)) p25(fmt(3)) p50(fmt(3)) p75(fmt(3))") append   

          * Panel D: dealer_ParInvChange_qtr (average across a combinaton of yyyyqq*CUSIP)
clear 
use Pseudo4RFS_dealer_ParInvChange_qtr
estpost tabstat dealer_parinvchange if ind_DNG==2, statistics(N mean  sd p25 p50 p75) columns(statistics) listwise   
esttab using DealerINVChange_sumstat.tex,  cells("count(fmt(0))  mean(fmt(3)) sd(fmt(3)) p25(fmt(3)) p50(fmt(3)) p75(fmt(3))") replace  
estpost tabstat dealer_parinvchange_lag if ind_DNG==2, statistics(N mean sd p25 p50 p75) columns(statistics) listwise   
esttab using DealerINVChange_sumstat.tex,  cells("count(fmt(0))  mean(fmt(3)) sd(fmt(3)) p25(fmt(3)) p50(fmt(3)) p75(fmt(3))") append   
estpost tabstat dealer_parinvchange if (ind_DNG==1 & ind_FallenInHY~=1) , statistics(N mean  sd p25 p50 p75) columns(statistics) listwise   
esttab using DealerINVChange_sumstat.tex, cells("count(fmt(0))  mean(fmt(3)) sd(fmt(3)) p25(fmt(3)) p50(fmt(3)) p75(fmt(3))") append  
estpost tabstat dealer_parinvchange_lag if (ind_DNG==1 & ind_FallenInHY~=1), statistics(N mean sd p25 p50 p75) columns(statistics) listwise   
esttab using DealerINVChange_sumstat.tex,  cells("count(fmt(0))  mean(fmt(3)) sd(fmt(3)) p25(fmt(3)) p50(fmt(3)) p75(fmt(3))") append   
estpost tabstat dealer_parinvchange if ind_Fallen==1, statistics(N mean  sd p25 p50 p75) columns(statistics) listwise   
esttab using DealerINVChange_sumstat.tex,  cells("count(fmt(0))  mean(fmt(3)) sd(fmt(3)) p25(fmt(3)) p50(fmt(3)) p75(fmt(3))") append  
estpost tabstat dealer_parinvchange_lag if ind_Fallen==1, statistics(N mean sd p25 p50 p75) columns(statistics) listwise   
esttab using DealerINVChange_sumstat.tex,  cells("count(fmt(0))  mean(fmt(3)) sd(fmt(3)) p25(fmt(3)) p50(fmt(3)) p75(fmt(3))") append   
estpost tabstat dealer_parinvlevel if ind_DNG==2, statistics(N mean  sd p25 p50 p75) columns(statistics) listwise   
esttab using DealerINVChange_sumstat.tex,  cells("count(fmt(0))  mean(fmt(3)) sd(fmt(3)) p25(fmt(3)) p50(fmt(3)) p75(fmt(3))") append  
estpost tabstat dealer_parinvlevel if (ind_DNG==1 & ind_FallenInHY~=1), statistics(N mean sd p25 p50 p75) columns(statistics) listwise   
esttab using DealerINVChange_sumstat.tex,  cells("count(fmt(0))  mean(fmt(3)) sd(fmt(3)) p25(fmt(3)) p50(fmt(3)) p75(fmt(3))") append   
estpost tabstat dealer_parinvlevel if ind_Fallen==1, statistics(N mean sd p25 p50 p75) columns(statistics) listwise   
esttab using DealerINVChange_sumstat.tex,  cells("count(fmt(0))  mean(fmt(3)) sd(fmt(3)) p25(fmt(3)) p50(fmt(3)) p75(fmt(3))") append   





     /*** Table 10: IV regressions  ***/ 
clear 
use Pseudo4RFS_cusip_level_reg_control_leverage
replace gp_rating=6 if gp_rating==7
replace gp_rating=2 if gp_rating==1
egen gpratingMatu=group(gp_maturity gp_rating)
collapse (mean) res change_inventory change_vix change_sveny10 change2_sveny10 change_slope change_sp  change_jump  change_inventory_IG , by(gpratingMatu yyyyqq) 
reshape wide res change_inventory change_vix  change_sveny10 change2_sveny10 change_slope change_sp  change_jump  change_inventory_IG, i(yyyyqq)  j(gpratingMatu)  
egen change_inventory=rowmean(change_inventory*)
egen change_vix=rowmean(change_vix*)
egen change_jump=rowmean(change_jump*)
egen change_sveny10=rowmean(change_sveny10*)
egen change2_sveny10=rowmean(change2_sveny10*)
egen change_slope=rowmean(change_slope*)
egen change_sp=rowmean(change_sp*)
egen change_inventory_IG=rowmean(change_inventory_IG*)
merge 1:1 yyyyqq using Pseudo4RFS_qchange_factors
drop if (yyyyqq>201502 | yyyyqq<200501)
egen INV=std(change_inventory)
pca res*, cov 
predict pc1 pc2 pc3 pc4 pc5 , score
tostring yyyyqq, replace
gen yyyy=substr(yyyyqq,1,4)
gen qq=substr(yyyyqq,5,2)
destring yyyy qq, replace
gen yyyymmdd=yyyy*10000+3*qq*100+20
tostring yyyymmdd, replace
format dt %td
gen yq = qofd(dt)
format yq %tq
tsset yq

replace  AllFund_HoldChangeFallen=AllFund_HoldChangeFallen/AllFund_HoldLevelDNG[_n]
egen Fallen=std(AllFund_HoldChangeFallen)    /* Fallen is standardized */
replace  AllFund_HoldChangeDNG=AllFund_HoldChangeHYDNG/AllFund_HoldLevelDNG[_n]
egen DNG=std(AllFund_HoldChangeDNG)          /* DNG is standardized */

foreach r of varlist res*   {
  replace `r'=`r'*90/100     /* quarter-change in percentage */
}
    * first-stage using Fallen as IV
ivreg2 INV Fallen STD_pc_noise_nonlinearLev DNG change_vix change_jump change_sveny10 change2_sveny10 change_slope change_sp, bw(auto) robust
outreg2 using reg_residual_IVInsuranceLoss, keep(INV Fallen DNG change_vix change_jump change_sveny10 change2_sveny10 change_slope change_sp  STD_pc_noise_nonlinearLev) stats(coef tstat) e(arfp archi2p sstatp) tex excel nolabel dec(3) coefastr replace
    * second-stage
ivreg2 res1 (INV=Fallen ) STD_pc_noise_nonlinearLev  DNG change_vix change_sveny10 change2_sveny10 change_slope change_sp, bw(auto) robust saverf 
outreg2 using reg_residual_IVInsuranceLoss, keep(INV Fallen pc_noise_nonlinearLev  STD_pc_noise_nonlinearLev ) stats(coef tstat) e(arfp archi2p sstatp) tex excel nolabel dec(3) coefastr replace
foreach r of varlist res*{
ivreg2 `r'  (INV=Fallen ) STD_pc_noise_nonlinearLev DNG change_vix change_sveny10 change2_sveny10 change_slope change_sp,  bw(auto) robust saverf
outreg2 using reg_residual_IVInsuranceLoss, keep(Fallen INV pc_noise_nonlinearLev  STD_pc_noise_nonlinearLev)  e(arfp archi2p sstatp) stats(coef tstat) tex excel nolabel dec(3) coefastr append
weakivtest, level(0.10)
}	




/*** Figure 2: plots of number of bonds, number of funds, and amount of holdings, by the group of pension, mutual, and insurance   ***/
clear
use Pseudo4RFS_Amt_InstitutionalHoldings
gen totalHolding_cum2=totalHolding1+totalHolding2
gen totalHolding_cum3=totalHolding1+totalHolding2 +totalHolding3
gen totalHolding_cum4=totalHolding1+totalHolding2 +totalHolding3+ cum_inventory_par
twoway area totalHolding1 yq, yaxis(1) || rarea totalHolding1 totalHolding_cum2 yq, yaxis(1) || rarea totalHolding_cum2 totalHolding_cum3 yq, yaxis(1) || rarea totalHolding_cum3 totalHolding_cum4 yq, yaxis(1) || (line FoF_corp_det yq, lpattern("solid") yaxis(1)  lcolor(black)), ///
legend( order(5 "Aggregate Outstanding" 4 "Dealer" 3 "Pension Fund" 2 "Mutual Fund" 1 "Insurance Company") pos(6) col(2)) xtitle("") ylabel(0(1)8.5, axis(1))  ytitle("\$ trillion",  axis(1) ) title("Amount of Institutional Holding and Dealer Inventory") 
graph export summay_holdamt.pdf, replace  /* Figure 2 top */

gen totalHolding1_ratio=100*totalHolding1/FoF_corp_det    /* insurance    */
gen totalHolding2_ratio=100*totalHolding2/FoF_corp_det    /* mutual fund  */
gen totalHolding3_ratio=100*totalHolding3/FoF_corp_det    /* pension fund */
gen totalInstitutional_ratio=100*totalHolding_cum3/FoF_corp_det   /* institutional= insurance+mutual+pension  */
gen totalDealer_ratio=100*cum_inventory_par/FoF_corp_det          /*  dealer */ 
gen totalHolding_ratio=100*totalHolding_cum4/FoF_corp_det         /*  institutional + dealer */
twoway                                                                                ///
	  (line totalInstitutional_ratio yq,  lpattern("dash_dot")  yaxis(1))     ///
	  (line totalHolding_ratio yq, lp("solid") yaxis(1)) ///	  
	  (line totalDealer_ratio yq, lpattern("longdash") yaxis(2)) ///
	  	   , legend( order(2 "By Dealers and Institutional Investors" 3 "By Dealers" 1 "By Institutional Investors") pos(6) col(2)) xtitle("") ylabel(0(5)40, axis(1)) ytitle("Percent",  axis(1) ) ytitle("Percent",  axis(2) )   title("Fraction of Aggregate Outstanding")
graph export summary_holding_delaer_2scale.pdf, replace  /* Figure 2 bottom*/





















